package com.fa4j.system.app.service.impl;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.base.util.ValidUtil;
import com.fa4j.system.app.convert.AppRoleConverter;
import com.fa4j.system.app.model.AppRole;
import com.fa4j.system.app.model.AppRoleCreateCmd;
import com.fa4j.system.app.model.AppRoleModifyCmd;
import com.fa4j.system.app.repository.AppRoleRepository;
import com.fa4j.system.app.service.AppRoleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 系统应用角色 服务接口实现
 *
 * @since 2025-07-14 11:04:33
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class AppRoleServiceImpl implements AppRoleService {

    private final AppRoleRepository appRoleRepository;
    private final AppRoleConverter appRoleConverter;

    /**
     * 新增系统应用角色
     *
     * @param cmd 新增参数
     * @return 系统应用角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppRole create(@Valid AppRoleCreateCmd cmd) {
        ValidUtil.validInUsed("角色编码", () -> appRoleRepository.findByAppAndCode(cmd.getAppType(), cmd.getCode()));
        AppRole entity = appRoleConverter.toEntity(cmd);
        appRoleRepository.create(entity);
        return entity;
    }

    /**
     * 编辑系统应用角色
     *
     * @param cmd 编辑参数
     * @return 系统应用角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppRole modify(@Valid AppRoleModifyCmd cmd) {
        AppRole entity = appRoleRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统应用角色"));
        appRoleConverter.updateEntity(entity, cmd);
        appRoleRepository.modify(entity);
        return entity;
    }

    /**
     * 删除系统应用角色
     *
     * @param cmd 删除参数
     * @return 系统应用角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppRole remove(@Valid RemoveCmd<Integer> cmd) {
        AppRole entity = appRoleRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统应用角色"));
        entity.setOperatorId(cmd.getOperatorId());
        appRoleRepository.remove(entity);
        return entity;
    }

}




